package com.tac.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tac.common.Exception.CostomException;
import com.tac.common.Exception.TokenException;
import com.tac.common.result.Result;
import com.tac.common.thread.Thread;
import com.tac.common.util.ImgUtis;
import com.tac.dao.*;
import com.tac.pojo.*;
import com.tac.pojo.vo.Page;
import com.tac.service.OrderService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.rmi.CORBA.Util;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderProductDao orderProductDao;
    @Autowired
    private CartDao cartDao;
    @Autowired
    private UserAddressDao userAddressDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private SaleDao saleDao;
    /**
     * 添加订单 直接计算购物车中选中的商品 生成订单快照
     * @param
     * @return
     */
    public Result save(Integer userAddressId,String setRemarks){
        //生成订单
        UserAddress userAddress = userAddressDao.selectById(userAddressId);
        Order order = new Order();
        order.setStatus(0);
        order.setProvince(userAddress.getProvince());
        order.setCity(userAddress.getCity());
        order.setArea(userAddress.getArea());
        order.setStreet(userAddress.getStreet());
        order.setCreateTime(LocalDateTime.now());
        List<Cart> carts = cartDao.selectByUidAndStaus(Thread.getId());
        if(carts.size()==0){
            throw  new CostomException("还没有选中商品");
        }
        BigDecimal bigDecimal = new BigDecimal(0);
        Integer quantity=0;
        for(Cart cart:carts){
            bigDecimal=bigDecimal.add(cart.getTotalPrice());
            quantity=quantity+cart.getQuantity();
        }
        order.setPrice(bigDecimal);
        order.setQuantity(quantity);
        order.setRemarks(setRemarks);
        order.setUserId(Thread.getId());
        orderDao.save(order);
        //生成订单快照
        for(Cart cart:carts){
            OrderProduct orderProduct = new OrderProduct();
            orderProduct.setOrderId(order.getId());
            orderProduct.setPrice(cart.getPrice());
            orderProduct.setProductId(cart.getProductId());
            orderProduct.setProductImg(cart.getProductImg());
            orderProduct.setProductName(cart.getProductName());
            orderProduct.setQuantity(cart.getQuantity());
            orderProduct.setTotalPrice(cart.getTotalPrice());
            orderProduct.setStatus(0);
            orderProductDao.save(orderProduct);
            //删除购物车
            cartDao.deleteById(cart.getId());
        }
        return Result.success(order.getId(),"success",201);
    }

    /**
     * 添加订单2 直接从商品详情中购买 生成订单快照
     * @param
     * @return
     */
    public Result save2(Integer pid,Integer quantity, Integer userAddressId,String setRemarks){

        //判断库存够不够
        Product product = productDao.selectById(pid);
        if(product.getStock()-quantity<0){
            throw  new CostomException("库存不足");
        }
        //生成订单
        UserAddress userAddress = userAddressDao.selectById(userAddressId);
        Order order = new Order();
        order.setStatus(0);
        order.setProvince(userAddress.getProvince());
        order.setCity(userAddress.getCity());
        order.setArea(userAddress.getArea());
        order.setStreet(userAddress.getStreet());
        order.setCreateTime(LocalDateTime.now());
        //计算购物车中商品的总价值

        order.setPrice(product.getPrice().multiply(new BigDecimal(quantity)));
        order.setQuantity(quantity);
        order.setRemarks(setRemarks);
        order.setUserId(Thread.getId());
        orderDao.save(order);
        //生成订单快照
            OrderProduct orderProduct = new OrderProduct();
            orderProduct.setOrderId(order.getId());
            orderProduct.setPrice(product.getPrice());
            orderProduct.setProductId(product.getId());
            orderProduct.setProductImg(product.getMainImage());
            orderProduct.setProductName(product.getName());
            orderProduct.setQuantity(quantity);
            orderProduct.setStatus(0);
            orderProduct.setTotalPrice(product.getPrice().multiply(new BigDecimal(quantity)));
            orderProductDao.save(orderProduct);

        return Result.success(order.getId(),"success",201);
    }

    /**
     * 根据id删除订单
     * @param oid
     * @return
     */
    public Result removeById(Integer oid){
        orderDao.removeById(oid);
        orderProductDao.remove(oid);
       return Result.success(null,"success",204);
    }

    /**
     * 更新订单 （主要更新状态用）
     * @param oid
     * @return
     */
    public Result updeteById(Integer oid,Integer status){

        Order order = orderDao.selectById(oid);
        Integer status1 = order.getStatus();
        if(status==1){

            //付款扣钱
            if(status1!=0){
                throw new CostomException("只有状态为未付款时才能付款");
            }
            User user = userDao.selecyById(Thread.getId());
            BigDecimal balance = user.getBalance();
            if(balance.compareTo(order.getPrice())>=0){
                user.setBalance(balance.subtract(order.getPrice()));
                userDao.updateByid(user);
            }else {
                order.setStatus(0);//钱不够生成待付款订单
                orderDao.updeteById(order);
                throw new CostomException("余额不足");
            }
            //判断库存够不够 减少库存，添加销量
            List<OrderProduct> orderProducts = orderProductDao.selectByOid(order.getId());
            for(OrderProduct orderProduct:orderProducts){
                Integer productId = orderProduct.getProductId();
                Integer quantity = orderProduct.getQuantity();
                Product product = productDao.selectById(productId);
                if(product.getStock()-quantity<0){
                    throw new CostomException("库存不足");
                }else {
                    //更新库存添加销量
                    product.setStock(product.getStock()-quantity);
                    product.setSalesVolume(product.getSalesVolume()+quantity);
                    productDao.updateById(product);
                    //添加销售表
                    Sale sale = new Sale();
                    sale.setUid(Thread.getId());
                    sale.setProductId(product.getId());
                    sale.setQuantity(quantity);
                    saleDao.save(sale);
                }

            }

        }
        if(status==4){
            //只有状态为未付款的时候才能取消
            if(status1!=0){
                throw new CostomException("只有状态为未付款的时候才能取消");
            }
        }
        if(status==2){
            if(status1!=1){
                throw new CostomException("只有状态为待收货的订单才能修改为待评价");
            }
        }
        if(status==3){
           // if(status1!=2){
                throw new CostomException("请使用评价接口");
            //}
        }
        order.setStatus(status);
        Integer integer = orderDao.updeteById(order);
        orderProductDao.updateStatus(status,oid);
        if(integer>0){
       return    Result.success(null,"success");
        }
        throw new CostomException("更新失败");
    }


    /**
     * 用户查看订单分页 时间排序
     * @param
     * @return
     */
    public Result<Page<List<Order>>> selectAll( Integer page,  Integer limit){

        List<Order> orders = orderDao.selectAll(Thread.getId(), (page - 1) * limit, limit);
        List<Order> orderList = new ArrayList<>();
        for(Order order :orders){
            List<OrderProduct> orderProducts = orderProductDao.selectByOid(order.getId());
            order.setOrderProducts(orderProducts);
            orderList.add(order);
        }
        Integer totalLimit = orderDao.selectAllCount(Thread.getId());
        Page<List<Order>> listPage = Page.get(orderList, totalLimit, limit);
        return Result.success(listPage,"success");
    }

    /**
     * 用户根据订单状态查看订单
     * @param status
     * @return
     */
    public Result<Page<List<Order>>> selectByStatus(Integer status, Integer page, Integer limit){

        List<Order> orders = orderDao.selectByStatus(status, Thread.getId(), (page - 1) * limit, limit);
        List<Order> orderList = new ArrayList<>();
        for(Order order :orders){
            List<OrderProduct> orderProducts = orderProductDao.selectByOid(order.getId());
            order.setOrderProducts(orderProducts);
            orderList.add(order);
        }
        Integer totalLimit = orderDao.selectByStatusCount(status,Thread.getId());
        Page<List<Order>> listPage = Page.get(orderList, totalLimit, limit);
        return Result.success(listPage,"success");
    }

    /**
     * 根据id查看详情
     * @param id
     * @return
     */
    public Result<Order> selectById(Integer id){
        Order order = orderDao.selectById(id);
        List<OrderProduct> orderProducts = orderProductDao.selectByOid(id);
        order.setOrderProducts(orderProducts);
        return Result.success( order,"success");
    }

    /**
     * 评价
     * @param comments
     * @return
     */
    public Result save(List<Comment> comments){

        for(Comment comment:comments){
            //判断订单快照状态是否为待评价2
            Integer orderId = comment.getOrderId();
            // Order order = orderDao.selectById(orderId);
            OrderProduct orderProduct = orderProductDao.selectByOrderIdAndProductId(orderId, comment.getProductId());
            Integer status = orderProduct.getStatus();
            if(status!=2){
                throw new CostomException("订单状态异常不能评价");
            }
            //保存评价
            User user = userDao.selecyById(Thread.getId());
            comment.setUserId(user.getId());
            comment.setUserName(user.getUsername());
            commentDao.save(comment);
            //修改订单快照状态为完成3
            orderProductDao.updateStatus2(orderProduct.getId(),3);
            //判断订单里的商品是否全部状态为已完成了 是的话给订单状态改为已完成
            List<OrderProduct> orderProducts = orderProductDao.selectByOid(orderId);
            boolean a=true;
            for(OrderProduct orderProduct1:orderProducts){
                Integer status1 = orderProduct1.getStatus();
                if(status1!=3){
                    a=false;
                }
            }
            if(a){
                Order order = orderDao.selectById(orderId);
                order.setStatus(3);
                orderDao.updeteById(order);
            }
        }

        return Result.success(null,"success");
    }
//------------------------------------------------------------------------------------------


    /**
     * 管理员查看所有订单
     * @return
     */
    public Result<PageInfo<Order>> selectAll2(Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Order> orders = orderDao.selectAll2();
        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
        return Result.success(orderPageInfo,"success");
    }
    /**
     * 管理员分类型查询订单等功能
     * @return
     */
    public Result<PageInfo<Order> >  selectByStatu2(Integer status,Integer pageNum,Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Order> orders = orderDao.selectByStatu2(status);
        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
        return Result.success(orderPageInfo,"success");
    }
}
